﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.WindowsAzure.StorageClient;
using System.Reactive.Linq;
using System.Reactive;
using System.Diagnostics.Contracts;
using RxCloud;

namespace Microsoft.WindowsAzure.StorageClient
{
    /// <summary>
    /// Extensions method for CloudQueue.
    /// </summary>
    public static class ClientExtensions
    {
        /// <summary>
        /// Converts CloudQueue to stream of messages.
        /// </summary>
        /// <param name="queue">Cloud queue</param>
        /// <param name="notifier">Notifier observer</param>
        public static IObserver<CloudQueueMessage> ToObserver(this CloudQueue queue, IObserver<Unit> notifier)
        {
            Contract.Requires(queue != null);
            Contract.Requires(notifier != null);
            Contract.Ensures(Contract.Result<IObserver<CloudQueueMessage>>() != null);

            return Observer.Create<CloudQueueMessage>(
                    m => queue.AddMessageAsync(m).Subscribe(notifier.OnNext, notifier.OnError),
                    notifier.OnError,
                    notifier.OnCompleted);
        }


        /// <summary>
        /// Converts CloudQueue to stream of messages.
        /// </summary>
        /// <param name="queue">Cloud queue</param>
        /// <param name="notificationsClient">Queue notifications client</param>
        public static IObserver<CloudQueueMessage> ToObserver(this CloudQueue queue, NotificationsClient notificationsClient)
        {
            Contract.Requires(queue != null);
            Contract.Requires(notificationsClient != null);
            Contract.Ensures(Contract.Result<IObserver<CloudQueueMessage>>() != null);

            return queue.ToObserver(notificationsClient.GetQueueNotifierObserver(queue.Name));
        }

    }
}
